package com.example.testdownload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.coe3.datahandler.BaseActivity;
import com.jotabout.zipdownloader.util.DecompressZip;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;

public class DecompressAsync extends AsyncTask<String, String, String>  {
	
	private BaseActivity activity = null;
	
	private String _zipFile; 
	private String _location;
	
	public DecompressAsync(MainActivity activity, String zipFile, String location) {
		this.activity = activity;
		_zipFile = zipFile; 
	    _location = location; 
	    
	    _dirChecker(""); 
	}
	
    @SuppressWarnings("deprecation")
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
        activity.showDialog( BaseActivity.DIALOG_CONNECTION_START );
    }

	@SuppressLint("WorldReadableFiles")
	@Override
    protected String doInBackground( String... aurl ) {
		
//		unzip();
		
		DecompressZip decomp = new DecompressZip( _zipFile, _location + File.separator );
		decomp.unzip();
		
        return null;
    }
    

    @SuppressWarnings("deprecation")
	@Override
    protected void onPostExecute(String unused) {
    	activity.dismissDialog(BaseActivity.DIALOG_CONNECTION_START );
    }
    
	  public void unzip() { 
	    try  { 
			FileInputStream fin = new FileInputStream(_zipFile); 
			ZipInputStream zin = new ZipInputStream(fin); 
			ZipEntry ze = null; 
			while ((ze = zin.getNextEntry()) != null) { 
				Log.v("Decompress", "Unzipping " + ze.getName()); 
			
			if(ze.isDirectory()) { 
				_dirChecker(ze.getName()); 
			} else { 
				FileOutputStream fout = new FileOutputStream(_location + ze.getName()); 
				for (int c = zin.read(); c != -1; c = zin.read()) { 
					fout.write(c); 
				} 
			
				zin.closeEntry(); 
				fout.close(); 
			} 
		
		}
		zin.close(); 
	} catch(Exception e) { 
		Log.e("Decompress", "unzip", e); 
		} 
		
	  } 

	  private void _dirChecker(String dir) { 
	    File f = new File(_location + dir); 

	    if(!f.isDirectory()) { 
	      f.mkdirs(); 
	    } 
	  } 
    
}
